package com.filldream.fastboot.core.service.websocket;

import com.filldream.fastboot.base.config.MyEndpointConfigure;
import com.filldream.fastboot.common.entity.B;
import com.filldream.fastboot.common.entity.R;
import com.filldream.fastboot.common.okutil.cls.dto.ClsNewsSimpleItem;
import com.filldream.fastboot.common.util.JsonUtil;
import com.filldream.fastboot.common.util.WsUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 财经消息推送
 * @author RickSun
 **/
@Slf4j
@Component
@ServerEndpoint(value = "/ws/clsNews", configurator = MyEndpointConfigure.class)
public class ClsNewsServer {

    /**
     * 连接集合
     */
    private static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        //先关闭老的链接
        final String sessionId = session.getId();
        Session oldSession = getSession(sessionId);
        if( oldSession != null ){
            unRoom(sessionId);
            WsUtil.close(  oldSession ,null);
        }
        //加入新的链接
        sessionMap.put(sessionId, session);
        //打印信息
        log.info("==============================================================");
        log.info("连接{}加入，连接数：{}",sessionId, sessionMap.size());
        log.info("==============================================================");
        //发送消息
        WsUtil.sendText(session, JsonUtil.toJson( B.success() ));
    }

    @OnClose
    public void onClose(Session session) {
        //发送关闭消息
        unRoom(session.getId());
        log.info("--------------------------------------------------------------");
        log.info("链接{}关闭，连接数：{}",session.getId(), sessionMap.size());
        log.info("--------------------------------------------------------------");
    }

    @OnError
    public void onError(Session session, Throwable error) {
        // 输出到日志文件中
        log.error(error.getMessage(), error);
    }

    /**
     * 根据sessionId获取session
     * @param sessionId
     * @return
     */
    public Session getSession(String sessionId) {
        if( sessionId.contains(sessionId) ){
            return sessionMap.get(sessionId);
        }
        return null;
    }

    /**
     * 移除session
     * @param sessionId
     */
    public void unRoom(String sessionId) {
        if( sessionId.contains(sessionId) ){
            sessionMap.remove(sessionId);
        }
    }

    /**
     * 获取连接集合
     * @return
     */
    public Map<String, Session> getSessionMap() {
        return sessionMap;
    }

    /**
     * 发送消息
     * @param waitSendList
     */
    public Boolean sendNewsList(List<ClsNewsSimpleItem> waitSendList){
        AtomicReference<Boolean> sendFlag = new AtomicReference<>(false);
        if(ObjectUtils.isNotEmpty(waitSendList)){
            Map<String, Session> sessionMap = getSessionMap();
            if( !sessionMap.isEmpty() ){
                sessionMap.forEach((sessionId,session)->{
                    Integer sendResult = WsUtil.sendText(session, JsonUtil.toJson(R.successd(waitSendList)));
                    if(sendResult == 1 && !sendFlag.get()){
                        sendFlag.set(true);
                    }
                });
            }
            return sendFlag.get();
        }
        return false;
    }

    /**
     * 发送消息
     * @param news
     */
    public Boolean sendNewsList(ClsNewsSimpleItem news){
        if( ObjectUtils.isNotEmpty(news) ){
            return sendNewsList(Arrays.asList(news));
        }
        return false;
    }

}
